import {Component} from "@angular/core";
import {ModalController, NavController, NavParams} from 'ionic-angular';
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {AjaxService} from "../../public/service/ajax.service";
import {SettingUrl} from "../../public/setting/setting_url";
import {MainService} from "../../public/service/main.service";
import {PatternService} from "../../public/service/pattern.service";

/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
declare const $;

@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  public loading;
  public loginForm: FormGroup = new FormGroup({
    loginAccount: new FormControl('', Validators.compose([Validators.required, Validators.pattern(PatternService.password), Validators.minLength(4), Validators.maxLength(16)])),
    pwd: new FormControl('', Validators.compose([Validators.required, Validators.pattern(PatternService.password), Validators.minLength(6), Validators.maxLength(16)])),
  });

  constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, private main: MainService) {
    // this.platform.ready().then(() => {
    //   this.backButtonService.registerBackButtonAction(null);
    // });
  }

  ionViewDidLoad() {
    let me = this;
    let user = window.localStorage.getItem('user');
    let pwd = window.localStorage.getItem('pwd');
    if(user && pwd){
      let userData = {
        loginAccount: user,
        pwd: pwd
      };
      $.when(me.loginData(userData).always(data => {
          me.main.user = data;
        this.navCtrl.setRoot('MenuPage');
          // this.navCtrl.push('TabsPage');
      }));
    }
  }

  /**
   * 登录
   * @param e 事件对象
   */
  logIn(e){
    let me = this;
    e.preventDefault();
    $.when(me.loginData(me.loginForm.value).always(data => {
        window.localStorage.setItem('user',me.loginForm.value.loginAccount);
        window.localStorage.setItem('pwd',me.loginForm.value.pwd);
        me.main.user = data;
        this.navCtrl.setRoot('MenuPage');
    }));
  }

  loginData(data){
    const me = this, defer = $.Deferred();  // 封装异步请求结果
    me.loading = me.main.loading();
    AjaxService.get({
      url: SettingUrl.URL.user.login+'/'+data.loginAccount+'/'+data.pwd,
      // data: data,
      success: res => {
        if (res.success) {
          defer.resolve(res.data);
        } else {
          me.main.toast('账号或密码错误!');
        };
        me.loading.dismiss();
      },
      error: _ => {
        me.loading.dismiss();
        me.main.toast();
      }
    });
    return defer.promise();
  }
}
